<template>
	<main-content
		:tableHeight.sync="tableHeight"
		:otherDependenComponents="otherDependenComponents"
	>
		<template slot="query">
			<el-form
				ref="formRef"
				:inline="true"
				:model="queryData"
				class="flex-warp-container"
			>
				<el-form-item class="flex-row-container">
					<el-select
						v-model="dateFlag"
						style="width:140px"
						:placeholder="$t('common.please_choose')"
					>
						<el-option
							:label="$t('report.statistics_data')"
							value="1"
						/>
						<el-option
							:label="$t('report.real_time_data')"
							value="0"
						/>
					</el-select>
					<el-date-picker
						v-model="searchTime"
						size="medium"
						:picker-options="pickerShortcutWithCurrPeriod"
						type="daterange"
						range-separator="-"
						:start-placeholder="$t('report.start_date')"
						:end-placeholder="$t('report.end_date')"
						:clearable="false"
						:disabled="dateFlag == 0"
					></el-date-picker>
				</el-form-item>
				<el-form-item>
					<el-button
						type="primary"
						icon="el-icon-search"
						size="medium"
						:disabled="loading"
						@click="search"
					>
						{{ $t('common.search') }}
					</el-button>
					<el-button
						icon="el-icon-refresh-left"
						size="medium"
						:disabled="loading"
						@click="reset"
					>
						{{ $t('common.reset') }}
					</el-button>
					<el-button
						v-if="hasPermission('90660044')"
						type="warning"
						icon="el-icon-download"
						size="medium"
						:disabled="loading"
						:loading="exportLoading"
						@click="handleExportExcel"
					>
						{{ $t('common.export') }}
					</el-button>
					<!-- <el-button
						type="success"
						icon="el-icon-sort"
						:disabled="loading"
						size="medium"
						@click="openColSettings"
					>
						{{ $t('common.row_set') }}
					</el-button> -->
				</el-form-item>
				<date-picker-shortcuts
					kind="shortcutForButtons"
					:action="handleShortcutBtnClick"
					:loading="loading"
				/>
			</el-form>
			<el-link :underline="false" type="danger">
				{{ $t('report.refresh_warning_text') }}
			</el-link>
		</template>
		<template slot="content">
			<el-table
				key="father"
				v-loading="loading"
				element-loading-spinner="el-icon-loading"
				border
				ref="elTable"
				size="mini"
				class="small-size-table"
				:data="tableData"
				style="width: 100%"
				show-summary
				@sort-change="changeTableSort"
				:max-height="tableHeight"
				highlight-current-row
				:summary-method="
					(val) => handleRow(val, subSummary, totalSummary)
				"
				:header-cell-style="getRowClass"
			>
				<template v-for="(itemParent, indexParent) in newCol">
					<el-table-column
						prop="staticsDate"
						align="center"
						:key="'column_' + indexParent"
						:prop="itemParent.prop"
						:align="itemParent.alignCenter"
						:label="itemParent.label"
						:min-width="itemParent.minWidth"
						:fixed="itemParent.isFixed"
						:sortable="itemParent.isSortColumn"
						:show-overflow-tooltip="itemParent.isShowTip"
						v-if="columnsAllIdObject[itemParent.id]"
					>
						<template slot="header" slot-scope="{ column, $index }">
							<span
								@mousedown="
									handleMounseDown($event, column, $index)
								"
								@dragover="
									handleDragover($event, column, $index)
								"
								v-if="itemParent.itemTipContent"
							>
								{{ itemParent.label }}
								<el-tooltip
									class="item"
									effect="dark"
									:content="itemParent.itemTipContent"
									placement="top-start"
								>
									<i class="el-icon-question"></i>
								</el-tooltip>
							</span>
							<span
								@mousedown="
									handleMounseDown($event, column, $index)
								"
								@dragover="
									handleDragover($event, column, $index)
								"
								v-else
							>
								{{ itemParent.label }}
							</span>
						</template>
						<template slot-scope="{ row }">
							<div v-if="itemParent.solt === 'numberSolt'">
								{{ handleNumber('', row[itemParent.prop], 0) }}
							</div>
							<div v-if="itemParent.solt === 'copySolt'">
								<Copy
									:title="row[itemParent.prop]"
									:copy="copy"
								>
									{{ row[itemParent.prop] }}
								</Copy>
							</div>
							<div v-if="itemParent.solt === 'businessModelSolt'">
								<p>
									{{
										mappingBusinessModel(
											row[itemParent.prop]
										)
									}}
								</p>
							</div>
							<div v-if="itemParent.solt === 'amountSolt'">
								<p
									:style="
										itemParent.soltColor
											? handleNumberColor(
													row[itemParent.prop]
											  )
											: ''
									"
								>
									{{
										handleTotalNumber(
											itemParent.currency,
											row[itemParent.prop]
										)
									}}
								</p>
							</div>
							<div v-if="itemParent.solt === 'defaultSolt'">
								<span>
									{{ row[itemParent.prop] }}
								</span>
							</div>
							<div v-if="itemParent.solt === 'statusSolt'">
								<span>
									{{ payoutStatusList[row[itemParent.prop]] }}
								</span>
							</div>
							<div v-if="itemParent.solt === 'popupSolt'">
								<el-link
									type="primary"
									@click="dialogDataSee(row)"
								>
									查看
								</el-link>
							</div>
							<div v-if="itemParent.solt === 'percentage'">
								<span>
									{{ (row[itemParent.prop] || 0) + '%' }}
								</span>
							</div>
						</template>
						<template v-for="(item, index) in itemParent.data">
							<el-table-column
								:key="'column_' + index"
								:prop="item.prop"
								:align="item.alignCenter"
								:label="item.label"
								:min-width="item.minWidth"
								:fixed="item.isFixed"
								:sortable="item.isSortColumn"
								:show-overflow-tooltip="item.isShowTip"
								v-if="columnsAllIdObject[item.id]"
							>
								<!-- 通过插槽为表头绑定mousedown和dragover方法 -->
								<template
									slot="header"
									slot-scope="{ column, $index }"
								>
									<span
										@mousedown="
											handleMounseDown(
												$event,
												column,
												$index
											)
										"
										@dragover="
											handleDragover(
												$event,
												column,
												$index
											)
										"
										v-if="item.itemTipContent"
									>
										{{ item.label }}
										<el-tooltip
											class="item"
											effect="dark"
											:content="item.itemTipContent"
											placement="top-start"
										>
											<i class="el-icon-question"></i>
										</el-tooltip>
									</span>
									<span
										@mousedown="
											handleMounseDown(
												$event,
												column,
												$index
											)
										"
										@dragover="
											handleDragover(
												$event,
												column,
												$index
											)
										"
										v-else
									>
										{{ item.label }}
									</span>
								</template>
								<template slot-scope="{ row }">
									<div v-if="item.solt === 'amountSolt'">
										<p
											:style="
												item.soltColor
													? handleNumberColor(
															row[item.prop]
													  )
													: ''
											"
										>
											{{
												handleTotalNumber(
													row.currency,
													row[item.prop]
												)
											}}
										</p>
									</div>
									<div v-if="itemParent.solt === 'copySolt'">
										<Copy
											:title="row[item.prop]"
											:copy="copy"
										>
											{{ row[item.prop] }}
										</Copy>
									</div>
									<div v-if="item.solt === 'defaultSolt'">
										<span>
											{{ row[item.prop] || '-' }}
										</span>
									</div>
									<div v-if="item.solt === 'popupSolt'">
										<el-link
											type="primary"
											@click="dialogData2(row)"
										>
											{{
												handleTotalNumber(
													row.currency,
													row[item.prop]
												)
											}}
										</el-link>
									</div>
									<div v-if="item.solt === 'percentage'">
										<span>
											{{ (row[item.prop] || 0) + '%' }}
										</span>
									</div>
								</template>
							</el-table-column>
						</template>
					</el-table-column>
				</template>
			</el-table>
			<!-- 分页 -->
			<el-pagination
				v-show="!!total"
				class="pageValue"
				:current-page.sync="pageNum"
				background
				layout="total, sizes,prev, pager, next, jumper"
				:page-size.sync="pageSize"
				:page-sizes="pageSizes"
				:total="total"
				:pager-count="9"
				@current-change="handleCurrentChange"
				@size-change="handleSizeChange"
			></el-pagination>
		</template>
		<detail-page
			v-if="visible"
			:detailData="detailData"
			:visible="visible"
			:memberDatas="memberDatas"
			:closeDialog="
				() => {
					visible = false
				}
			"
		/>
	</main-content>
</template>

<script>
import list from '@/mixins/list'
import dayjs from 'dayjs'
import { routerNames } from '@/utils/consts'
import summaryList from './components/summaryList'
import MainContent from '@/components/MainContent/index.vue'
import DatePickerShortcuts from '@/components/DatePickerShortcuts'
import IncomeDetailDialog from '@/components/Funds/ProxyIncome/incomeDetailDialog.vue'
import { getColumns } from './components/columns'

const setSearchTime = () => [
	dayjs()
		.startOf('day')
		.valueOf(),
	dayjs()
		.startOf('day')
		.valueOf()
]
export default {
	name: routerNames.dataComparisonReport,
	components: {
		DatePickerShortcuts,
		IncomeDetailDialog,
		MainContent
	},
	mixins: [list, summaryList],
	data() {
		return {
			tableHeight: 480,
			curData: {},
			otherDependenComponents: [],
			queryData: { inputType: 1, accountLevelList: [] },
			exportLoading: false,
			queryData: {},
			proxyleveList: [],
			newCol: '',
			searchTime: setSearchTime(),
			tableData: [],
			subSummary: {},
			memberDatas: [],
			totalSummary: {},
			businessModelList: [
				{
					description: '现金业务',
					code: '1'
				},
				{
					description: '信用业务',
					code: '2'
				}
			],
			dateFlag: '1',
			merchantObj: '',
			defaultProps: {
				children: 'data',
				label: 'label'
			},
			axiosDate: '',
			visible: false,
			detailData: {},
			colSettings: {
				visible: false,
				dialogColumnData: {}
			},
			activityListField: {},
			settlementStatusList: [
				{
					description: '无收益',
					code: '5'
				},
				{
					description: '待发放',
					code: '1'
				},
				{
					description: '已发放',
					code: '3'
				},
				{
					description: '已取消',
					code: '6'
				}
			],
			payoutStatusList: {
				1: '待发放',
				3: '已发放',
				5: '无收益',
				6: '已取消'
			},
			columnsAllIdObject: {},
			columnsAllId: [],
			detailVisible: false,
			detailTableData: [],
			proxyAccountInfo: {}
		}
	},
	computed: {},
	watch: {},
	created() {
		this.newCol = getColumns()
		for (const index in this.newCol) {
			let e = this.newCol[index]
			this.columnsAllIdObject[e.id] = e.id
			this.columnsAllId.push(e.id)
			for (let j in e.data) {
				this.activityListField[e.data[j].label] = true
				this.columnsAllIdObject[e.data[j].id] = e.data[j].id
				this.columnsAllId.push(e.data[j].id)
			}
		}
		this.initIndexDB('statusOverView', this.activityListField)
		this.getProxyleve()
	},
	mounted() {},
	methods: {
		handleCheckChange(checkedKeys, info) {
			this.columnsAllIdObject = {}
			this.columnsAllId = []
			let ids = this.$refs.tree.getCheckedNodes()
			for (const index in ids) {
				let e = ids[index]
				this.columnsAllIdObject[e.id] = e.id
				this.columnsAllId.push(e.id)
			}
		},
		getProxyleve() {
			this.$api.getProxylevelnameList().then((res) => {
				this.proxyleveList = res.data || []
			})
		},
		handleShortcutBtnClick(val) {
			this.searchTime = val
			this.search()
		},
		// 提交列设置数据
		handleOrderList() {
			this.colSettings.visible = false
			this.updateIndexDB()
		},
		// 打开列设置弹框
		openColSettings() {
			this.getIndexDB(this.activityListField)
			this.colSettings.visible = true
		},
		clickDel() {
			for (const index in this.newCol) {
				let e = this.newCol[index]
				this.columnsAllIdObject[e.id] = e.id
				this.columnsAllId.push(e.id)
				for (let j in e.data) {
					this.columnsAllIdObject[e.data[j].id] = e.data[j].id
					this.columnsAllId.push(e.data[j].id)
				}
			}
			this.$refs.tree.setCheckedKeys(this.columnsAllId)
		},
		changeTableSort({ column, prop, order }) {
			this.queryData.orderKey = prop
			if (order === 'ascending') {
				// 升序
				this.queryData.orderType = 'asc'
			} else if (column.order === 'descending') {
				// 降序
				this.queryData.orderType = 'desc'
			} else {
				delete this.queryData.orderKey
				delete this.queryData.orderType
			}
			this.loadData()
		},
		loadData() {
			if (+new Date() - 500 < this.axiosDate) return
			const timeArr = this.searchTime || []
			let params = {
				...this.queryData,
				dataAreaType: Number(this.dateFlag),
				startDate:
					this.dateFlag === '1'
						? dayjs(timeArr[0]).format('YYYYMMDD')
						: undefined,
				endDate:
					this.dateFlag === '1'
						? dayjs(timeArr[1]).format('YYYYMMDD')
						: undefined
			}
			params = this.getParams(params)
			this.tableData = []
			const minM = dayjs(timeArr[0])
			const maxM = dayjs(timeArr[1])
			const month = dayjs(maxM).diff(minM, 'month')
			if (month >= 12) {
				this.$message.warning(this.$t('report.12_month'))
				this.total = 0
				return
			}
			this.loading = true
			this.pageCurrency = this.merchantObj?.currency || ''
			this.$api
				.getStatusPlatViewList(params)
				.then((res) => {
					this.loading = false
					this.axiosDate = +new Date()
					this.tableData = res?.data?.record || []
					this.total = res?.data?.totalRecord || 0
					this.subSummary = res?.data?.summary || {}
				})
				.catch(() => {
					this.loading = false
				})
			this.$api
				.getStatusPlatViewTotal(params)
				.then((res) => {
					this.loading = false
					this.totalSummary = res?.data || {}
				})
				.catch(() => {
					this.loading = false
				})
		},
		search() {
			this.pageNum = 1
			this.loadData()
		},
		reset() {
			this.pageNum = 1
			this.queryData = {}
			this.merchantObj = ''
			this.dateFlag = '1'
			this.searchTime = setSearchTime()
			if (this.$refs.elTable) {
				this.$refs.elTable.clearSort()
			}
			this.loadData()
		},
		handleExportExcel() {
			const timeArr = this.searchTime || []
			const params = {
				...this.queryData,
				dataAreaType: Number(this.dateFlag),
				startDate: dayjs(timeArr[0])
					.startOf('day')
					.format('YYYYMMDD'),
				endDate: dayjs(timeArr[1])
					.endOf('day')
					.format('YYYYMMDD')
			}
			this.exportLoading = true
			this.exportExcelPublic({
				api: 'getStatusPlatViewExport',
				params
			}).finally(() => {
				this.exportLoading = false
			})
		},
		queryServiceRateAmountFun(row) {
			this.detailTableData = []
			const params = {
				proxyId: row.proxyId,
				reportDate: row.reportDate
			}
			const loading = this.$loading({
				lock: true,
				text: 'Loading',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			})
			this.$api
				.queryServiceRateAmount(params)
				.then((res) => {
					loading.close()
					this.proxyAccountInfo = res.data.proxyResp
					let e = res.data.serviceAmountRateRespDTO
					let e1 = {
						project: e.venueName,
						serviceChargeHandContribution: this.handleTotalNumber(
							'USDT',
							e.serviceChargeHandContribution
						),
						serviceChargeRoundContribution: this.handleTotalNumber(
							'USDT',
							e.serviceChargeRoundContribution
						),
						serviceAmountContribution: this.handleTotalNumber(
							'USDT',
							e.serviceAmountContribution
						)
					}
					let e2 = {
						project: '占比',
						serviceChargeHandContribution: this.handlePercentage(
							e.serviceChargeHandContributionRate
						),
						serviceChargeRoundContribution: this.handlePercentage(
							e.serviceChargeRoundContributionRate
						),
						serviceAmountContribution: this.handlePercentage(
							e.serviceAmountContributionRate
						)
					}
					this.detailTableData.push(e1)
					this.detailTableData.push(e2)
				})
				.catch(() => {
					loading.close()
					this.visible = false
					this.auditDialog.loading = false
				})
		}
	}
}
</script>

<style lang="scss" scoped>
.tips-box {
	position: absolute;
	right: 10px;
	top: 50%;
	margin-top: -12px;
}
::v-deep .el-dialog__header {
	color: #909399;
	font-weight: 700;
}
::v-deep .el-table__fixed-footer-wrapper .cell,
::v-deep .el-table__footer-wrapper .cell {
	height: 100%;
	padding: 0 !important;
	margin: 0 !important;
	> div {
		height: 100%;
	}
}
::v-deep .footer_count_row {
	min-height: 50px;
	height: 50%;
	display: flex;
	font-weight: 700;
	padding: 5px 0;
	align-items: center;
	flex-direction: column;
	justify-content: center;
}
::v-deep .footer_count_row_border {
	border-top: 1px solid #ebeef5;
}
::v-deep .is-group th {
	background-color: #f5f7fa !important;
}
::v-deep .el-icon-question:after {
	font-size: 16px;
	margin-left: 0;
}
::v-deep .el-table th.el-table__cell > .cell {
	text-align: center;
}
</style>
